import React, { useState, useEffect } from 'react';
import { Modal, Card, Button, message } from 'antd';
import type { TableListItem } from '../data';
import { getViewCode } from '../service';

export type FormValueType = {} & Partial<TableListItem>;


export type ViewFormProps = {
    onCancel: (flag?: boolean, formVals?: FormValueType) => void;
    onSubmit: (values: FormValueType) => Promise<void>;
    viewModalVisible: boolean;
    values: Partial<TableListItem>;
};


const ViewForm: React.FC<ViewFormProps> = (props) => {
    const [activeKey, setActiveKey] = useState<any>('');
    const [tabList, setTabList] = useState<any>([]);
    const [contentList, setContentList] = useState<any>([]);
    const [content, setContent] = useState<any>([]);

    useEffect(() => {
        if(props.values.id!=''&&props.values.id!=null){
            findViewCode();
        }
    }, [props.viewModalVisible]);

    const findViewCode = async () => {
        const hide = message.loading('正在查询');
        try {
            await getViewCode(props.values.id).then(res => {
                console.log(res);
                var data = res.data;

                let tabLs = [];
                for (var i = 0; i < data.length; i++) {
                    if (i == 0) {
                        setActiveKey(data[i].name);
                        setContent(data[i].content)
                    }
                    tabLs.push({
                        key: data[i].name,
                        tab: data[i].name,
                    })
                }
                setTabList(tabLs);
                setContentList(data);
            })
            hide();
            return true;
        } catch (error) {
            hide();
            return false;
        }
    };

    const handleCancel = () => {
        props.onCancel()
    }

    return (
        <Modal
            width={1000}
            title='预览'
            visible={props.viewModalVisible}
            destroyOnClose
            onCancel={handleCancel}
            footer={[
                <Button key="back" onClick={() => {
                    props.onCancel()
                }}>
                    关闭
                </Button>
            ]}
        >
            <Card
                style={{ width: '100%' }}
                title="预览"
                tabList={tabList}
                activeTabKey={activeKey}
                onTabChange={key => {
                    setActiveKey(key)
                    contentList.map((item: any) => {
                        if (item.name == key) {
                            console.log(item.content)
                            setContent(item.content);
                        }
                    })
                }}
            >
                <pre dangerouslySetInnerHTML={{ __html: content }} ></pre>
                {/* {content} */}
            </Card>
        </Modal >
    );
};

export default ViewForm;
